package com.jingfu.controller;

import com.jingfu.Service.UserService;
import com.jingfu.common.AccountStatusException;
import com.jingfu.common.BadRequestException;
import com.jingfu.common.ErrorCode;
import com.jingfu.dto.PassEditDTO;
import com.jingfu.dto.SysPowerDTO;
import com.jingfu.dto.UserAddDTO;
import com.jingfu.dto.UserDTO;
import com.jingfu.util.CommonResult;
import com.jingfu.util.PageResult;
import com.jingfu.util.PageUtil;
import com.jingfu.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;


/**
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2021/4/1 4:16 下午
 * @description 处理登录，使用shiro中的FormAuthenticationFilter自动提交登录，只需要处理一些跳转逻辑
 **/
@Controller
@Slf4j
public class UserController {
    @Autowired
    UserService userService;


    @RequestMapping(value = "user/login", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(HttpServletRequest req) {
        if (req.getMethod().equalsIgnoreCase(RequestMethod.GET.name())) {
            //转发到登录页，注意配置了视图解析器就不能加forward关键字，即，return "forward:login",转发则不受影响，还是使用"redirect:/login.jsp
            return "login";
        }
        String errorClassName = (String) req.getAttribute("shiroLoginFailure");
        if (UnknownAccountException.class.getName().equals(errorClassName) || AccountException.class.getName().equals(errorClassName)) {
            throw new BadRequestException(ErrorCode.USER_NAME_OR_PASSWORD_ERROR);
        } else if (IncorrectCredentialsException.class.getName().equals(errorClassName)) {
            throw new BadRequestException(ErrorCode.USER_NAME_OR_PASSWORD_ERROR);
        } else if (ErrorCode.VERTIFY_CODE_ERROR.name().equals(errorClassName)) {
            throw new BadRequestException(ErrorCode.VERTIFY_CODE_ERROR);
        } else if (AccountStatusException.class.getName().equals(errorClassName)) {
            throw new BadRequestException(ErrorCode.ACCOUNT_HAS_FORBIDDEN);
        } else if (errorClassName != null) {
            req.setAttribute("error", "未知错误：" + errorClassName);
        }
        //登录成功不会走这里，走FormAuthenticationFilter#onLoginSuccess()
        throw new BadRequestException(ErrorCode.USER_LOGIN_ERROR);
    }

    /**
     * 登录成功，shiro跳转的路径
     *
     * @return
     */
    @RequestMapping(value = {"/login-sucess"}, method = {RequestMethod.GET})
    @ResponseBody
    public CommonResult loginSuccess() {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            throw new BadRequestException(ErrorCode.UNAUTHORIZED);
        }
        return CommonResult.ok().build();
    }

    /**
     * 登录成功，shiro跳转的路径
     *
     * @return
     */
    @RequestMapping(value = {"/index"}, method = {RequestMethod.GET})
    public String index(Model model) {
        model.addAttribute("currentUser",UserUtil.getCurrentUser().get());
        return "index";
    }

    /**
     * 返回当前登录者的所有菜单
     *
     * @return
     */
    @RequestMapping(value = "user/menu", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<SysPowerDTO.MenuDTO>> getUserMenu() {
        List<SysPowerDTO.MenuDTO> list = userService.getMenuListForCurrentUser();
        return CommonResult.ok(list);
    }


    /**
     * 用户查询列表
     *
     * @return
     */
    @RequestMapping(value = "/user/list", method = RequestMethod.GET)
    @ResponseBody
    public PageResult<List<UserDTO>> getUserList(UserDTO userDTO) {
        PageUtil.startPage();
        List<UserDTO> users = userService.getUserList(userDTO);
        return PageUtil.buidPage(users);
    }

    /**
     * 用户列表页视图
     *
     * @return
     */
    @RequestMapping(value = "/user-index", method = RequestMethod.GET)
    public String getUserIndex() {
        return "system/user";
    }

    /**
     * 用户新增页面视图
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/user-add-view", method = RequestMethod.GET)
    public String getUserAddView(Model model) {
        model.addAttribute("roleList", userService.queryAllRoles());
        return "system/operate/userAdd";
    }

    @RequestMapping("/user/create")
    @ResponseBody
    public CommonResult createUser(@RequestBody UserAddDTO userAddDTO) {
        log.info("用户新增请求，参数：{}", userAddDTO);
        userService.createOrUpdateUser(userAddDTO);
        return CommonResult.ok().build();
    }

    @RequiresPermissions("sys:user:remove")
    @RequestMapping("/user/remove/{userId}")
    @ResponseBody
    public CommonResult removeUser(@PathVariable String userId) {
        log.info("请求删除用户，用户Id:{}",userId);
        userService.removeUser(userId);
        return CommonResult.ok().build();
    }

    @RequiresPermissions("sys:user:remove")
    @RequestMapping("/user/batch-remove/{userId}")
    @ResponseBody
    public CommonResult batchRemoveUser(@PathVariable String userId) {
        log.info("请求批量删除用户，用户Id:{}",userId);
        Arrays.stream(userId.split(",")).forEach(id->{
            userService.removeUser(id);
        });
        return CommonResult.ok().build();
    }

    /**
     * 用户状态切换
     * @param userId
     * @param enable 1-激活 0-禁用
     * @return
     */
    @RequestMapping("/user/enable/{userId}/{enable}")
    public CommonResult userEnable(@PathVariable String userId,@PathVariable String enable) {
        userService.userEnable(userId, enable);
        return CommonResult.ok().build();
    }

    /**
     * 用户修改页面视图
     * @param model
     * @return
     */
    @RequestMapping(value = "/user-edit-view", method = RequestMethod.GET)
    public String getUserEditView(Model model) {
        //当前用户
        model.addAttribute("user", UserUtil.getCurrentUser().get());
        //系统所有角色
        model.addAttribute("roleList", userService.queryAllRoles());
        return "system/operate/userEdit";
    }

    /**
     * 用户基础信息视图
     * @param model
     * @return
     */
    @RequestMapping("/user-base-view")
    public String getUserBaseView(Model model) {
        model.addAttribute("currentUser",UserUtil.getCurrentUser().get());
        return "system/person";
    }

    /**
     * 更新用户基础信息
     * @param userAddDTO
     * @return
     */
    @RequestMapping("/user/update-base-info")
    @ResponseBody
    public CommonResult updateUserBaseInfo(@RequestBody UserAddDTO userAddDTO) {
        log.info("用户基础修改请求，参数：{}", userAddDTO);
        userService.updateUserBaseInfo(userAddDTO);
        return CommonResult.ok().build();
    }

    /**
     * 用户密码修改视图
     * @param model
     * @return
     */
    @RequestMapping("/pass-edit-view")
    public String getPassEditView(Model model) {
        return "system/operate/passEdit";
    }

    /**
     * 修改用户密码
     * @param passEditDTO
     * @return
     */
    @RequestMapping("/user/pass-edit")
    @ResponseBody
    public CommonResult userPassEdit(@RequestBody PassEditDTO passEditDTO) {
        userService.userPassEdit(passEditDTO);
        return CommonResult.ok().build();
    }

    @RequestMapping("/user-avatar-view")
    public String getUserAvatarView(Model model) {
        model.addAttribute("currentUser",UserUtil.getCurrentUser().get());
        return "system/operate/uploadProfile";
    }

    @RequestMapping("/user-avatar/upload")
    @ResponseBody
    public CommonResult userAvatarUpload(@RequestParam("file") MultipartFile file, @RequestParam String fileName, @RequestParam String userId,HttpServletRequest  request) {
        userService.userAvatarUpload(file,userId,fileName,request);
        return CommonResult.ok().build();
    }

}

